package com.example.itcompanyinterview;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.itcompanyinterview.object.Problem;
import com.example.itcompanyinterview.tools.CommonJsonParser;
import com.example.itcompanyinterview.tools.CommonUrlRequest;
import com.example.itcompanyinterview.tools.CustomTitleSetter;
import com.example.itcompanyinterview.tools.LoadingDialogHelper;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class ProblemDetailActivity extends Activity {

	private Problem _problem;
	private CustomTitleSetter _titleSetter;
	private Handler _messageHandler;
	private LoadingDialogHelper _loadingHelper;
	
	private static String PROBLEM_CONTROLLER = "Problem";
	private static String GET_PROBLEM_ACTION = "GetProblemContentAndAnswer";
	private static String GET_PREV_PROBLEM_ACTION = "GetPrevProblem";
	private static String GET_NEXT_PROBLEM_ACTION = "GetNextProblem";
	private static int PROBLEM_RETREIVE = 0x08;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_problem_detail);
		this.Initialize();
		this.getProblemFromUrl(this.GET_PROBLEM_ACTION);
	}
	
	private void Initialize() {
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		this._problem = (Problem)bundle.getSerializable("problem");
		
		this._titleSetter = new CustomTitleSetter(this);
		this._titleSetter.setTitle(this._problem.getTitle(), View.GONE, View.VISIBLE);
		
		this._loadingHelper = new LoadingDialogHelper(this);
		this.initMessageHandler();
		this.addMenuClickAction();
	}

	private void initMessageHandler() {
		this._messageHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (msg.what == PROBLEM_RETREIVE) {
					_loadingHelper.closeLoadingDialog();
					String problemJsonString = (String) msg.obj;
					if (problemJsonString == null) {
						Toast.makeText(ProblemDetailActivity.this,
								"获取题目失败，请检测网络", Toast.LENGTH_SHORT).show();
						return;
					}
					initProblemDetail(problemJsonString);
				}
				super.handleMessage(msg);
			}

		};
	}
	
	private void addMenuClickAction() {
		this.addToPrevProblemAction();
		this.addToNextProblemAction();
	}
	
	private void addToPrevProblemAction() {
		TextView prevProblem = (TextView)this.findViewById(R.id.prev_problem);
		prevProblem.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				getProblemFromUrl(ProblemDetailActivity.GET_PREV_PROBLEM_ACTION);
			}
		});
	}
	
	private void addToNextProblemAction() {
		TextView nextProblem = (TextView)this.findViewById(R.id.next_problem);
		nextProblem.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				getProblemFromUrl(ProblemDetailActivity.GET_NEXT_PROBLEM_ACTION);
			}
		});
	}

	private void getProblemFromUrl(final String problemAction) {
		new Thread(new Runnable() {
			public void run() {
				List<Pair<String, String>> paramList = new ArrayList<Pair<String, String>>();
				CommonUrlRequest.setParam(paramList, "problem_id",
						String.valueOf(_problem.getId()));
				CommonUrlRequest.setParam(paramList, "sub_cid", 
						String.valueOf(_problem.getSubCategoryId()));
				String problemJsonString = CommonUrlRequest
						.getControllerAndAction(
								ProblemDetailActivity.PROBLEM_CONTROLLER,
								problemAction,
								paramList);
				Message m = _messageHandler.obtainMessage();
				m.obj = problemJsonString;
				m.what = ProblemDetailActivity.PROBLEM_RETREIVE;
				_messageHandler.sendMessage(m);
			}
		}).start();
		this._loadingHelper.showLoadingDialog();
	}

	private void initProblemDetail(String contentJson) {
		try {
			TextView problemContentView = (TextView) this
					.findViewById(R.id.problemDetail);

			JSONObject jsonProblemObj = CommonJsonParser
					.parseJsonObject(contentJson);
			if (jsonProblemObj.getInt("err") != 0) {
				Toast.makeText(ProblemDetailActivity.this,
						jsonProblemObj.getString("msg"),
						Toast.LENGTH_LONG).show();
				return;
			}

			JSONObject jsonQuestion = CommonJsonParser
					.parseJsonObject(jsonProblemObj.getString("value"));
			
			int id = jsonQuestion.getInt("id");
			int subCategoryId = jsonQuestion.getInt("subcid");
			String problemTitle = jsonQuestion.getString("title");
			String problemContent = jsonQuestion.getString("content");
			String problemAnswer = jsonQuestion.getString("answer");
			this._problem.setId(id);
			this._problem.setSubCategoryId(subCategoryId);
			this._problem.setTitle(problemTitle);
			this._problem.setContent(problemContent);
			this._problem.setAnswer(problemAnswer);

			this._titleSetter.changeTitle(this._problem.getTitle());
			String problemText = this._problem.getContent() + "\n\n-------\n\n"
								+ this._problem.getAnswer();
			problemContentView.setText(problemText);
		} catch (JSONException e) {
			Toast.makeText(ProblemDetailActivity.this, "获取题目异常",
					Toast.LENGTH_LONG).show();
			Log.e("InitQuestionContent", e.getMessage());
		}
	}
	

}
